import { nodePath } from './path.node';
import { CRLF } from './constant';
import { Config } from './../entrance';
import { joinPath, toPosix } from "./path.node";
import { toCamelStyle, toUnderLineStyle, toLineStyle } from "./string";
import { nodeFileSystem } from "./fs.node";

function writeFile(file: string, tpl: string, shortName: string, config: Config) {
    if (nodeFileSystem.existsSync(file) && !config.rewrite) {
        console.log("****[ exist target file ]*********error: log start>>>>[ exist target file ]>>>>>>>>>>>>>");
        console.log("write file error: [ exist target file ] -> " + shortName);
        console.log(file);
        console.log(shortName + "已存在");
        console.log("<<<<[ exist target file ]<<<<<<<error: log end********[ exist target file ]**********");
        return;
    }
    nodeFileSystem.writeFile(file, tpl, "utf8", (err) => {
        if (err) {
            console.log("*************error: log start>>>>>>>>>>>>>>>>>");
            console.log("write file error: " + shortName);
            console.log(file);
            console.error(err);
            console.log("<<<<<<<<<<<error: log end******************");
        } else {
            console.log("-------------success: log start>>>>>>>>>>>>>>>>>");
            console.log("write file success: " + shortName);
            console.log(file);
            console.log("<<<<<<<<<<<success: log end---------------");
        }
    });
}

function writeScssFile(folder: string, componentName: string, config: Config) {
    const shortName = componentName + ".scss";
    const file = joinPath(folder, shortName);
    let tpl = config.initStyles.map(style => {
        const styleFile = joinPath(config.root, config.codeRoot, style);
        return `@import "${toPosix(nodePath.relative(nodePath.dirname(file), styleFile)).replace(/\.scss$/, "")}";`;
    }).join(CRLF);
    tpl += `
.c-${toLineStyle(componentName)} {}
`;
    writeFile(file, tpl, shortName, config);
}

function writeVueFile(folder: string, componentName: string, config: Config) {
    const shortName = componentName + ".vue";
    const file = joinPath(folder, shortName);
    const underLineStyleName = toLineStyle(componentName);
    const tpl = `<template>
    <div class="c-${underLineStyleName}">
    </div>
</template>

<script>
import "./${componentName}.scss";
// import scss style file <==

export default {
    name: "${underLineStyleName}",
};
</script>
`;
    writeFile(file, tpl, shortName, config);
}

export function writeVueJSFile(folder: string, componentName: string, config: Config) {
    const camelName = toCamelStyle(componentName);
    writeVueFile(folder, camelName, config);
    writeScssFile(folder, camelName, config);
}